package com.iamteer.dao.impl;

import java.util.List;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import com.iamteer.dao.ICategoryDao;
import com.iamteer.entity.Category;
import com.iamteer.utils.JdbcUtils;
/**
 * 2. 菜系 DAO 实现
 * @author Chuck
 *
 */
public class CategoryDao implements ICategoryDao {
	private QueryRunner qr = JdbcUtils.getQueryRunner();
	
	@Override
	public void add(Category category) {
		try {
			String sql = "insert into category(cName) values(?)";
			qr.update(sql, category.getcName());
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	@Override
	public void update(Category category) {
		try {
			String sql = "update category set cName=? where id=?";
			qr.update(sql, category.getcName(), category.getId());
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	@Override
	public void delete(int id) {
		try {
			String sql = "delete from category where id=?";
			qr.update(sql, id);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	@Override
	public Category findById(int id) {
		try {
			String sql = "select * from category where id=?";
			return qr.query(sql, new BeanHandler<Category>(Category.class), id);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	@Override
	public List<Category> query() {
		try {
			String sql = "select * from category";
			return qr.query(sql, new BeanListHandler<Category>(Category.class));
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	@Override
	public List<Category> query(String keyword) {
		try {
			String sql = "select * from category where cName like ?";
			keyword = "%" + keyword + "%";
			return qr.query(sql, new BeanListHandler<Category>(Category.class), keyword);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	@Override
	public Integer getFirst() {
		try {
			String sql = "select * from category";
			return qr.query(sql, new ScalarHandler<Integer>());
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
}
